import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { FileUploader } from 'ng2-file-upload';
import { DomSanitizer } from "@angular/platform-browser";
import { LoadingController, Loading } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { ImagePicker,ImagePickerOptions } from '@ionic-native/image-picker';
import { ActionSheetController } from 'ionic-angular';


/**
 * Generated class for the ComplainPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-complain',
  templateUrl: 'complain.html',
})
export class ComplainPage {

  help: any[] = new Array<any>();

  remarks: any;

  // 字典相关
  dictionary: Dictionary[] = new Array<Dictionary>();
  group: Group[] = new Array<Group>();

  // 问题类型
  problem_type: any;

  // 订单信息
  charging: Charg = new Charg();

  cell_name: any;

  selectedImgUrl: any[] = [];//存储已经选择的图片
  selectedImgLength = 0;
  // 图片base64
  base64: Img[] = new Array<Img>();

  constructor(
    public navCtrl: NavController,
    public viewCtrl: ViewController,
    public navParams: NavParams,
    public http: HttpProvider,
    public storage: StorageProvider,
    public dialog: DialogProvider,
    public user: UserInfoProvider,
    private sanitizer: DomSanitizer,
    private camera: Camera,
    private imagePicker: ImagePicker,
    public actionSheetCtrl: ActionSheetController,
    public loadingCtrl: LoadingController) { }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ComplainPage');

    this.charging = this.navParams.get('data');
    this.cell_name = this.charging.q_charging_pile.chargingpile.cell_name;
    // console.log(this.charging);

    // this.storage.getStorage("login_info").then(res => {
    //   if (res != undefined) {
    //     this.member_id = res['member_id']
    //   }
    // });


    this.storage.getStorage("dictionary").then(res => {
      if (res) {
        this.dictionary = JSON.parse(res);

        this.getDictionary();
      }
    });
  }

  ionViewDidEnter() {
    this.base64.splice(0);
  }

  /**
   * 上传申述
   */
  getComplain() {
    if (!this.problem_type) {
      this.dialog.showAlert('请选择申述的问题类型', '');
      return;
    }
    if (!this.remarks) {
      this.dialog.showAlert('请输入问题描述', '');
      return;
    }
    let loading = this.loadingCtrl.create({
      content: '正在上传申述...'//数据加载中显示
    });
    loading.present();
    this.http.postJson('', 'business/appeal/create',
      {
        "order_code": this.charging.charge_code,
        "power_unit_id": this.charging.power_unit_id,
        "member_id": this.user.userInfo.member_id,
        "application_time": new Date().getTime().toString().slice(0, 10),
        "representa_state": "0",
        "problem_type": this.problem_type,
        "remarks": this.remarks,
        "is_del": "0"
      }, '').then(res => {
        // console.log(res)
        if (res['status'] == 200) {
          if (this.base64.length > 0) {
            this.saveImg(res['data']['appeal_id']);
          }
          loading.dismiss();
          this.dialog.showAlert('申述成功', '');

          this.navCtrl.setRoot('CenterPage');
          this.navCtrl.parent.select(2);
        } else {
          loading.dismiss();
          this.dialog.showAlert('申述失败', '');
        }
      });

  }

  getMessage(help) {
    this.help.splice(0);
    console.log(help)
    for (let message of help) {
      if (message) {
        var a = {
          /*根据提供的接口地址传参数,配置文件在http.ts里查看,里面写的是链接服务器的配置*/
          img: this.http.APP_IMG + message.url,
          titles: message.titles,
          description: message.description,
        };
        this.help.push(a);
      }
    }
    // console.log(this.help);
  }

  /**
   * 寻找字典
   */
  getDictionary() {
    let map = new Array<Group>();
    for (let d of this.dictionary) {
      if (d.D_GROUP === 'PROBLEM_TYPE') {
        map = d.group;
      }
    }
    this.group = map;
  }

  /**
* 选择问题类型
*/
  chooseValue(i) {
    this.problem_type = this.group[i].D_VALUE;
    // console.log(this.problem_type);
  }

  presentActionSheet() {
    const actionSheet = this.actionSheetCtrl.create({
      title: '请选择',
      buttons: [
        {
          text: '拍照',
          role: 'destructive',
          handler: () => {
            console.log('拍照 clicked');
            this.takePhoto();
          }
        },{
          text: '相册',
          handler: () => {
            console.log('相册 clicked');
            this.selectPhoto();
          }
        },{
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('取消 clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }
  
  takePhoto(){
   	const options: CameraOptions = {
	  quality: 50,
	  destinationType: this.camera.DestinationType.DATA_URL,
	  encodingType: this.camera.EncodingType.JPEG,
	  mediaType: this.camera.MediaType.PICTURE,
//	  allowEdit:true,
//	  sourceType:this.camera.PictureSourceType.CAMERA,
	};
//	let _this2 = this;
	this.camera.getPicture(options).then((imageData) => {
		 // imageData is either a base64 encoded string or a file URI
		 // If it's base64 (DATA_URL):
		 let base64Image = 'data:image/jpeg;base64,' + imageData;
//		 this.dialog.showAlert('1提示imageData', '');
		 
//		 this.selectedImgUrl[0] = base64Image;
//		 this.base64Img = base64Image;
//		 this.base64name = 'userNow.jpg';
		 this.selectedImgUrl.push(base64Image);
		 let a = {
	          img: base64Image,
	          name: 'fileImg.jpg',
	     }
	        //就是base64
	     this.base64.push(a);
		 
	}, (err) => {
	 // Handle error
	});
   }
   selectPhoto(){
   	const options: CameraOptions = {
	  quality: 50,
	  destinationType: this.camera.DestinationType.DATA_URL,
	  encodingType: this.camera.EncodingType.JPEG,
	  mediaType: this.camera.MediaType.PICTURE,
	  sourceType:this.camera.PictureSourceType.PHOTOLIBRARY,
//	  allowEdit:true,
	};
	this.camera.getPicture(options).then((imageData) => {
		 // imageData is either a base64 encoded string or a file URI
		 // If it's base64 (DATA_URL):
		 let base64Image = 'data:image/jpeg;base64,' + imageData;
		 
//		 this.selectedImgUrl[0] = base64Image;
//		 this.base64Img = base64Image;
//		 this.base64name = 'userNow.jpg';
		 
		 this.selectedImgUrl.push(base64Image);
		 let a = {
	          img: base64Image,
	          name: 'fileImg.jpg',
	     }
	        //就是base64
	     this.base64.push(a);
		 
	}, (err) => {
	 // Handle error
	});
   	
    }
  
  /**
   * 压缩图片
   * @param file 
   * @param w 
   * @param objDiv 
   */
//photoCompress(file, w, objDiv) {
//  let _this = this;
//  var ready = new FileReader();
//  /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
//  ready.readAsDataURL(file);
//  ready.onload = function () {
//    var re = this.result;
//
//    _this.canvasDataURL(re, w, objDiv)
//  }
//}
/*  canvasDataURL(path, obj, callback) {
    var img = new Image();
    img.src = path;
    img.onload = function () {
      var that = img;
      // 默认按比例压缩
      var w = that.width,
        h = that.height,
        scale = w / h;
      w = obj.width || w;
      h = obj.height || (w / scale);
      //              w = 300;
      //              h = 300;
      var quality = 0.2;  // 默认图片质量为0.7(主要改下面的配置)
      //生成canvas
      var canvas = document.createElement('canvas');
      var ctx = canvas.getContext('2d');
      // 创建属性节点
      //              var anw = document.createAttribute("width");
      //              anw.nodeValue = w;
      //              var anh = document.createAttribute("height");
      //              anh.nodeValue = h;
      //              canvas.setAttributeNode(anw);
      //              canvas.setAttributeNode(anh);
      //替代
      canvas.width = w;
      canvas.height = h;
      ctx.drawImage(that, 0, 0, w, h);
      // 图像质量
      if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
        quality = obj.quality;
      }
      // quality值越小，所绘制出的图像越模糊
      var base64 = canvas.toDataURL('image/jpeg', quality);
      // 回调函数返回base64的值
      callback(base64);
    }
  }*/

  /**
   * 选择图片
   * @param event 
   */
 /* upLoadImg(event) {
    //this.selectedImgUrl.splice(0);
    // console.log(event);
    if (!event) {
      return;
    }
    if (!event.target.files[0]) {
      return;
    }
    var fileImg = event.target.files[0];
    let promise = new Promise((success) => {
      let _this2 = this;
      _this2.photoCompress(fileImg, {
        quality: 0.5
      }, function (base64Codes) {
        // console.log("dd:__" + base64Codes);
        _this2.selectedImgUrl.push(base64Codes);
        //			_this2.base64Img=base64Codes;

        let a = {
          img: base64Codes,
          name: fileImg.name,
        }
        //就是base64
        _this2.base64.push(a);
      });

      //    var reader = new FileReader();
      //    this.selectedImgUrl.push(this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(fileImg)));
      //    reader.readAsDataURL(fileImg);
      //    reader.onload = function (e) {
      //      success(this);
      //    }
    });

    //回调
    promise.then(data => {
      //    let a = {
      //      img: data['result'],
      //      name: fileImg.name,
      //    }
      //    //就是base64
      //    this.base64.push(a);
    })
    // //上传成功
    // event.target.value = "";

  }*/

  /**
   * 上传图片
   * @param appeal_id 
   */
  async saveImg(appeal_id) {
    this.http.postJson('', 'member/member/headportrait',
      {
        "product_id": appeal_id,//附件ID
        "file_type_id": "6",//附件类型 1.会员头像，2.营业执照扫描件，3.合同扫描件，4.营业执照扫描件，5.安装场地，6.申诉信息图片,7广告文件，8软文展示图，9电表记录表    
        "tables": "7",//所属表1会员表2主体表3物业表4广告表5软文表6电表记录表7申诉表   
        "base64_img_list": this.base64
      }, '').then(res => {
        console.log(res);
      });

  }

  //删除图片
  deleteimg(i) {
    this.selectedImgUrl.splice(i, 1);
    this.base64.splice(i, 1);
  }


}








export class Dictionary {
  D_GROUP: any;
  group: Group[];
}

export class Group {
  D_ID: any;
  D_NAME_CN: any;
  D_NAME_EN: any;
  D_GROUP: any;
  D_PID: any;
  D_VALUE: any;
  D_INDEX: any;
  D_STATE: any;
  D_HTML: any;
  D_REMARKS: any;
}

export class Charg {
  member_charge_id: any;
  charge_code: any;
  charge_time_start: any;
  charge_time_end: any;
  charge_time: any;
  power_unit_id: any;
  member_id: any;
  payment_money: any;
  discount_money: any;
  refund_money: any;
  order_money: any;
  payment_id: any;
  states: any;
  created_at: any;
  updated_at: any;
  cuser_id: any;
  uuser_id: any;
  tables: any;
  q_charging_pile: {
    chargingpile: any;
    charging_pile_id: any;
    charging_pile_name: any;
    cell_name: any;
  }
}

export class Img {
  img: any;
  name: any;
}

